import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'model/group_model.dart';
import 'widget/gradient_button.dart';
import 'util/ui_data.dart';
import 'dart:io';

class RegisterPage extends StatefulWidget {
  final Color mainColor;
  RegisterPage(this.mainColor);
  @override
  _RegisterPageState createState() => new _RegisterPageState(mainColor);
}

class _RegisterPageState extends State<RegisterPage> {
  _RegisterPageState(this.mainColor);
  final Color mainColor;
  List<GroupModel> groups = [];
  String selectedGroup;
  final scaffoldState = GlobalKey<ScaffoldState>();
  String account = "";
  String password = "";
  String smsCode = "";
  String imgCode = "";
  String imgCodeUrl = "";
  int reSend = -1;
  int isReg = 0;
  bool hidePass = false;
  final GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  @override
  void initState() {
    super.initState();
    initGroups();
  }

  Future<bool> willPop() {
    Navigator.of(context).pop(isReg);
    return new Future.value(false);
  }

  initGroups() async {
    var existGroups = await getGroups();
    for (var i = 0; i < existGroups.length; i++) {
      groups.add(
        new GroupModel(id: existGroups[i]['id'], name: existGroups[i]['name'], devices: []),
      );
    }
    this.selectedGroup = groups[0].name;
    setState(() {});
  }

  String validateAccount(String value) {
    if (value == "") return "请输入手机号/邮箱";
    return null;
  }

  String validatePassword(String value) {
    if (value == "") return "请输入密码";
    return null;
  }

  startTimer() async {
    if (!mounted) {
      return;
    }
    if (this.reSend == -1) {
      this.reSend = 60;
      startTimer();
      if (mounted) {
        setState(() {});
      }
    } else if (this.reSend == 0) {
      this.reSend = -1;
    } else {
      new Timer(new Duration(seconds: 1), () {
        this.reSend = this.reSend - 1;
        startTimer();
        if (mounted) {
          setState(() {});
        }
      });
    }
  }

  showImgCodeAlert(Map imageCode) {
    showDialog<Null>(
      context: context,
      barrierDismissible: false,
      builder: (context) {
        return new AlertDialog(
          title: new Text("图片验证码"),
          content: new Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              new Image.file(new File(imageCode['path'])),
              new TextField(
                onChanged: (verifyCode) {
                  this.smsCode = verifyCode;
                },
                style: new TextStyle(fontSize: 15.0, color: Colors.black),
                decoration: new InputDecoration(
                  hintText: "请输入图片验证码",
                ),
              ),
            ],
          ),
          actions: <Widget>[
            new FlatButton(
              child: new Text(
                "获取验证码",
              ),
              padding: EdgeInsets.all(0.0),
              onPressed: () async {
                var sendResult = await getSmsCode(this.account, imgCode: this.smsCode, codeKey1: imageCode['codeKey1'], codeKey2: imageCode['codeKey2']);
                this.smsCode = "";
                print(sendResult);
                Navigator.of(context).pop();
                if (sendResult['iRet'] == 0) {
                  toast("验证码发送成功");
                } else if (sendResult['iRet'] == -121) {
                  toast("图片验证码错误");
                  var imageCode = await getImageCode(imgCodeUrl);
                  showImgCodeAlert(imageCode);
                } else if (sendResult['iRet'] == -122) {
                  toast("请输入图片验证码");
                  showImgCodeAlert(imageCode);
                } else {
                  toast(sendResult['sMsg']);
                }
              },
            ),
            new FlatButton(
              onPressed: () async {
                Navigator.of(context).pop();
              },
              child: new Text(
                '关闭',
              ),
            ),
          ],
        );
      },
    );
  }

  register() async {
    var exist = await findDeviceByAccount(account);
    if (exist) {
      toast("账号已存在");
      return false;
    }
    Map checkCode = await checkSmsCode(this.account, this.smsCode);
    if (checkCode['iRet'] == 0) {
      Map regResult = await doRegister(this.account, this.password, this.smsCode);
      if (regResult['iRet'] == 0) {
        toast("注册成功");
        this.isReg = 1;
        var groupid = 1;
        for (GroupModel group in groups) {
          if (group.name == selectedGroup) {
            groupid = group.id;
            break;
          }
        }
        addDevice(groupid, account, password, rand(), rand(), rand(), rand());
      } else {
        toast(regResult['sMsg']);
      }
    } else {
      toast(checkCode['sMsg']);
    }
  }

  @override
  void dispose() {
    // TODO: implement dispose
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
      child: Scaffold(
          key: scaffoldState,
          appBar: new CupertinoNavigationBar(
            border: new Border(bottom: BorderSide.none),
            actionsForegroundColor: Colors.white,
            backgroundColor: mainColor,
            middle: new Text(
              "注册玩客云账号",
              style: new TextStyle(
                color: Colors.white,
                fontWeight: FontWeight.normal,
              ),
            ),

          ),
          body: new ListView(
            children: <Widget>[
              new Column(
                children: <Widget>[
                  new Container(
                    height: 100.0,
                    child: ClipPath(
                      clipper: new ArcClipper(),
                      child: Stack(
                        children: <Widget>[
                          new Container(
                            decoration: new BoxDecoration(
                              gradient: new LinearGradient(
                                begin: Alignment.topCenter,
                                end: Alignment.bottomCenter,
                                colors: [mainColor, mainColor],
                              ),
                            ),
                          ),
                          new Container(
                            width: double.infinity,
                            child: Image.asset(
                              "images/wky_logo.png",
                              width: 40.0,
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                  new Center(
                    child: Column(
                      children: <Widget>[
                        SizedBox(
                          height: 20.0,
                        ),
                        new Card(
                          margin: EdgeInsets.all(20.0),
                          color: Colors.white,
                          elevation: 2.0,
                          child: Form(
                            key: _formKey,
                            child: Padding(
                              padding: const EdgeInsets.all(18.0),
                              child: new Column(
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  new TextFormField(
                                    decoration: new InputDecoration(
                                      hintText: '请输入手机号/邮箱',
                                      labelText: "账号",
                                    ),
                                    onSaved: (value) {
                                      this.account = value;
                                    },
                                    validator: validateAccount,
                                  ),
                                  new TextFormField(
                                    obscureText: this.hidePass,
                                    decoration: new InputDecoration(
                                      hintText: '请输入玩客云密码',
                                      labelText: '密码',
                                      suffixIcon: new IconButton(
                                        icon: new Icon(
                                          this.hidePass ? Icons.visibility : Icons.visibility_off,
                                          color: Colors.black38,
                                          size: 22.0,
                                        ),
                                        onPressed: () {
                                          this.hidePass = !this.hidePass;
                                          setState(() {});
                                        },
                                      ),
                                    ),
                                    onSaved: (value) {
                                      this.password = value;
                                    },
                                    validator: validatePassword,
                                  ),
                                  new TextFormField(
                                    decoration: new InputDecoration(
                                      hintText: '请输入验证码',
                                      labelText: '验证码',
                                      suffixIcon: new FlatButton(
                                        child: new Text("发送验证码"),
                                        onPressed: () async {
                                          final FormState form = _formKey.currentState;
                                          form.save();
                                          if (this.account == "") {
                                            toast("请输入手机号/邮箱");
                                            return;
                                          }
                                          var sendResult = await getSmsCode(this.account, sessionid: "", userid: "");
                                          this.smsCode = "";
                                          if (sendResult['iRet'] == 0) {
                                            toast("验证码发送成功");
                                          } else if (sendResult['iRet'] == -122) {
                                            toast("请输入图片验证码");
                                            this.imgCodeUrl = sendResult['sMsg'];
                                            var imageCode = await getImageCode(sendResult['sMsg']);
                                            print(imageCode);
                                            showImgCodeAlert(imageCode);
                                          } else {
                                            toast(sendResult['sMsg']);
                                          }
                                        },
                                      ),
                                    ),
                                    onSaved: (value) {
                                      this.smsCode = value;
                                    },
                                    validator: validatePassword,
                                  ),
                                  new DropdownButtonHideUnderline(
                                    child: new SafeArea(
                                      child: new InputDecorator(
                                        decoration: const InputDecoration(
                                          labelText: '分组',
                                          hintText: '请选择分组',
                                        ),
                                        child: new DropdownButton<String>(
                                          //style: TextStyle(color: Colors.black),
                                          isDense: true,
                                          value: selectedGroup,
                                          hint: new Text("请选择分组"),
                                          onChanged: (value) {
                                            setState(() {
                                              selectedGroup = value;
                                            });
                                          },
                                          items: groups.map((GroupModel group) {
                                            return new DropdownMenuItem<String>(
                                              value: group.name,
                                              child: new Text(group.name),
                                            );
                                          }).toList(),
                                        ),
                                      ),
                                    ),
                                  ),
                                  new SizedBox(
                                    height: 30.0,
                                  ),
                                  new GradientButton(
                                    onPressed: () async {
                                      final FormState form = _formKey.currentState;
                                      if (!form.validate()) {
                                      } else {
                                        form.save();
                                        register();
                                      }
                                    },
                                    text: "注册并添加",
                                    splashColor: mainColor,
                                  ),
                                  new SizedBox(
                                    height: 10.0,
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                  )
                ],
              ),
            ],
          ),),
      onWillPop: willPop,
    );
  }
}
